/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cratos.xxgram.platf.base;

import java.util.function.Consumer;
import java.util.logging.*;
import javax.annotation.Resource;
import javax.persistence.Transient;

import org.redkale.net.http.WebSocketNode;
import org.redkale.service.*;
import org.redkale.source.DataSource;
import org.redkale.util.AnyValue;
import org.redkale.util.Comment;

import com.cratos.xxgram.platf.file.FileService;
import com.cratos.xxgram.platf.message.MessageRecord;
import com.cratos.xxgram.platf.util.QueueTask;

/**
 *
 * @author zhangjx
 */
public abstract class BaseService extends AbstractService {

    protected static final boolean winos = System.getProperty("os.name").contains("Window");

    protected final Logger logger = Logger.getLogger(this.getClass().getSimpleName());

    protected final boolean finer = logger.isLoggable(Level.FINER);

    protected final boolean finest = logger.isLoggable(Level.FINEST);

    @Resource(name = "platf")
    protected DataSource source;
    
    @Resource(name = "wsim")
    protected WebSocketNode webSocketNode;
    
    @Comment("插入对象队列")
    public final QueueTask<BaseEntity> insertQueue = new QueueTask<>(1);

    @Comment("修改对象队列")
    public final QueueTask<Runnable> updateQueue = new QueueTask<>(1);

    @Comment("删除消息队列对象队列")
    public final QueueTask<Runnable> deleteQueue = new QueueTask<>(1);

    @Transient //WS消息缓存队列
    public final QueueTask<Runnable> wsmessageQueue = new QueueTask<>(1);
    
    @Resource
	protected FileService fileService;
    
    @Override
    public void init(AnyValue config) {
    	// TODO Auto-generated method stub
    	super.init(config);
    	Consumer<BaseEntity> insertConsumer = (BaseEntity record) -> {
			try {
				if (record instanceof MessageRecord) {
					MessageRecord msgRecord = (MessageRecord) record;
					source.insert(msgRecord.copyhis());
				}
				source.insert(record);
			} catch (Exception e) {
				e.printStackTrace();
			}
		};
		insertQueue.init(logger, insertConsumer);
		updateQueue.init(logger, task -> task.run());
		deleteQueue.init(logger, task -> task.run());
		wsmessageQueue.init(logger, task -> task.run());
    }
    
	@Override
	public void destroy(AnyValue config) {
		insertQueue.destroy();
		updateQueue.destroy();
		deleteQueue.destroy();
		wsmessageQueue.destroy();
	}
}
